package com.example.mq.config.es;

import com.alibaba.fastjson.JSONObject;
import com.example.mq.dto.Doc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 邹宇杰
 * @email 2901570623@qq.com
 * @site http://zouyujie.top
 * @date 2022/3/15 19:07
 */
@Component
public class ElasticService {

    @Autowired
    RestHighLevelClient client;

    @Value("${es.indices}")
    private String indices;

    /**
     * 插入文档数据
     * @param index 文档索引
     * @param id 文档id
     * @param str 文档源
     * @return 响应数据
     */
    public RestStatus insertDoc(String index, String id, String str) throws IOException {
        IndexRequest indexRequest = new IndexRequest(index).id(id);
        indexRequest.timeout("1s");
        indexRequest.source(str,  XContentType.JSON);
        return client.index(indexRequest, RequestOptions.DEFAULT).status();
    }

    /**
     * 删除文档数据
     * @param doc 完整文档数据
     * @return 响应状态
     */
    public RestStatus deleteDoc(Doc doc) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(doc.getIndex()).id(doc.getId());
        return client.delete(deleteRequest, RequestOptions.DEFAULT).status();
    }

    /**
     * 更新文档数据
     * @param doc 需要被更新的文档
     * @return 响应状态
     * @throws IOException
     */
    public RestStatus updateDoc(Doc doc) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(doc.getIndex(), doc.getId());
        updateRequest.doc(JSONObject.toJSONString(doc), XContentType.JSON);
        return client.update(updateRequest, RequestOptions.DEFAULT).status();
    }

    /**
     * 创建索引
     * @return 创建索引是否成功
     * @throws IOException
     */
    public Boolean create() throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indices);
        return client.indices().create(createIndexRequest, RequestOptions.DEFAULT).isAcknowledged();
    }

    /**
     * 查找索引是否存在
     * @param indices 索引名字
     * @return 该索引是否存在
     * @throws IOException
     */
    public Boolean exists(String indices) throws IOException {
        GetIndexRequest getRequest = new GetIndexRequest(indices);
        return client.indices().exists(getRequest, RequestOptions.DEFAULT);
    }
}
